import { FC, useEffect, useState } from 'react'
import Taro from "@tarojs/taro"
import "taro-ui/dist/style/components/tabs.scss";
import { Subscription, tap } from 'rxjs'
import { View, Text, Button, Image, ScrollView } from '@tarojs/components'
import { AtTabs, AtTabsPane, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtInput } from 'taro-ui'
import "taro-ui/dist/style/components/button.scss" // 按需引入 
import { useAuthFacade } from '@/hooks/useAuthFacade'
import { softWarePrice } from '@/models/request/userReq'
import { formatTimeDate } from '@/utils';
import { PlanOptions, Plans, SubscriptionRsp } from '@/models/response/userRsp';
import { PLAN_VERSIONS, SOFTWARE } from '@/constants/subscription';
import './index.scss'

export const ServiceCenter: FC = () => {
  const [authFacade, , , , orgs, userInfo] = useAuthFacade();
  const [tabCurrent, setTabCurrent] = useState(0) //选中的套餐current值
  const [allPackage, setAllPackage] = useState([] as Plans[])//所有套餐数据
  const [tabList, setTabList] = useState([] as any) //套餐项的标题  
  const [allPlans, setAllPlans] = useState({} as Plans)  // 套餐项
  const [price, setPrice] = useState(0) //单月套餐价格
  const [yearPrice, setYearPrice] = useState(0) //套餐年价格
  const [planName, setPlanName] = useState('') //套餐名字
  const [currentPlanId, setCurrentPlanId] = useState('')  //套餐id
  const [options, setOptions] = useState([] as PlanOptions[])  // 功能项 
  const [current, setCurrent] = useState(0) //选中的套餐  
  const [currentMsg, setCurrentMsg] = useState({} as SubscriptionRsp)  // 已订阅信息
  const [inputVal, setInputVal] = useState('');  //获取输入框的值
  const [editRounds, setEditRounds] = useState(false)//修改场次提示框显/隐
  const [roundsVal, setRoundsVal] = useState('');  //自定义购买场次的值
  //  旗舰版单场套餐
  const roundsList = [
    {
      rounds: '10',
      priceRound: 500,
      total: 500 * 10,
    },
    {
      rounds: '1',
      priceRound: 500,
      total: 500 * 1,
    },
    {
      rounds: roundsVal == '' ? '自定义' : roundsVal,
      priceRound: 500,
      total: 500 * parseInt(roundsVal),
    },
  ]

  // 套餐类型与价格
  const priceList: softWarePrice[] = [
    {
      priceTime: '一年',
      total: yearPrice,
      discount: yearPrice - (price * 12),
      oldTotal: price * 12
    },
    {
      priceTime: '三个月',
      total: price * 3,
    },
    {
      priceTime: '一个月',
      total: price,
    },
  ]

  //获取自定义输入的值
  const getInputTipsVal = (val: string) => {
    setInputVal(val);
  }

  //隐藏/显示公告提示框
  const setRoundsShow = () => {
    setEditRounds(false)
    setRoundsVal('0')
  }

  //确认修改场次
  const setRounds = () => {
    setEditRounds(false)
    setRoundsVal(inputVal)
  }

  // 按年折扣计算，选择的月份每满一年就按年折价
  const getYearFullPrice = (monthPrice: number) => {
    return monthPrice * 12;
  }

  //比较两个套餐的差异，返回不同的部分
  const getSubDiff = (planCode: string) => {
    let prevPlan = [] as PlanOptions[] | undefined; //前一版本
    const curPlan = allPackage.find(item => item.planCode === planCode)?.options as PlanOptions[] | undefined; //当前选择版本 
    switch (planCode) {
      case PLAN_VERSIONS.ENTERPRISE: //企业版，前一个版本是旗舰版
        {
          prevPlan = allPackage.find(item => item.planCode === PLAN_VERSIONS.ULTIMATE)?.options;
          break;
        }
      case PLAN_VERSIONS.ULTIMATE: //旗舰版，前一个版本是高级版
        {
          prevPlan = allPackage.find(item => item.planCode === PLAN_VERSIONS.ADVANCED)?.options;
          break;
        }
      case PLAN_VERSIONS.ADVANCED: //高级版，前一个版本是标准版
        {
          prevPlan = allPackage.find(item => item.planCode === PLAN_VERSIONS.STANDARD)?.options;
          break;
        }
      case PLAN_VERSIONS.STANDARD: //标准版显示全部内容
      default:
        break;
    }

    let res = [] as PlanOptions[];

    if (curPlan) {
      //返回当前版本比前一个版本多出的功能
      res = curPlan.filter(item => prevPlan && !prevPlan.some(item2 => item2.optionValue === item.optionValue))
    }
    setOptions(res)
    return res
  }

  // 点击套餐
  const handleClick = (e) => {
    setTabCurrent(e)
    const arr = allPackage[e]
    const arr1 = allPackage[e - 1]
    // const planOptions1 = arr1.map(value => Object.assign({}, { title: value.planName }))  
    // 点击的套餐是否是当前的套餐
    // if (e != 0) {
    getSubDiff(arr.planCode)
    // }
    setAllPlans(arr)
    setPrice(arr.priceMonth)
    setPlanName(arr.planName)
    setCurrentPlanId(arr.plan_id)
    setCurrent(0)
    // setOptions(arr.options)
    setYearPrice(arr.priceYear)
  }
  // 点击激活码
  const goToActivation = () => {
    Taro.navigateTo({
      // url: '/pages/my/activation/index'
      url: '/subPages/my/activation/index'
    })
  }

  // 点击支付
  const goToPay = () => {
    Taro.navigateTo({
      // url: `/pages/my/pay/index?priceMonth=${price}&priceYear=${yearPrice}&planName=${planName}&current=${current}&planId=${currentPlanId}&roundsVal=${roundsVal}`
      url: `/subPages/my/pay/index?priceMonth=${price}&priceYear=${yearPrice}&planName=${planName}&current=${current}&planId=${currentPlanId}&roundsVal=${roundsVal}`
    })
  }


  // 点击套餐价格
  const handleCheckPrice = (e) => {
    console.log('点击触发', e.currentTarget.dataset);
    const index = e.currentTarget.dataset.index;
    setCurrent(index)
    if (index === 2 && allPlans.planName === '旗舰版单场') {
      setEditRounds(true)
    }
  }

  //获取软件id,接着获取套餐和订阅信息
  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      // 获取所有套餐项
      authFacade.AllPlanInfo(SOFTWARE.ZYL)
        .pipe(
          tap(res => {
            console.log('res的值为:', res)
            setAllPackage(res)
            setAllPlans(res[0])
            const arr = res[0]
            const item = res.map(value => Object.assign({}, { title: value.planName }))
            // 赋值给一个新的数组变量
            const newarr = item.slice(0, 5);
            console.log('newItem的值为:', newarr)
            setTabList(newarr)
            setOptions(arr.options)
            setPrice(arr.priceMonth)
            setYearPrice(arr.priceYear)
            setPlanName(arr.planName)
            setCurrentPlanId(arr.plan_id)
            setCurrent(0)
            getYearFullPrice(arr.priceMonth)
          })
        )
        .subscribe(),
      //获取已订阅信息
      authFacade.getSubs()
        .pipe(
          tap(res => {
            console.log('所有订阅信息', res);
            setCurrentMsg(res)
          })
        )
        .subscribe()
    ]
    return () => { subscriptions.map(sub => sub.unsubscribe()) }
  }, [])

  return (
    <View className='index'>
      <View className='top'>
        {/* 用户信息 */}
        <View className={tabCurrent === 0 ? "top-model" : 'top-model top-model-bck'}>
          <View className='avator'>
            <Image src={userInfo.avatarUrl} ></Image>
          </View>
          <View className='nickName'>
            <View className='userName'>{userInfo.nickName}</View>
            <View className='desc'>{currentMsg.planCode === PLAN_VERSIONS.STANDARD ? '标准版：' + formatTimeDate(new Date(currentMsg.expires)) + ' 到期' : currentMsg.planCode === PLAN_VERSIONS.ADVANCED ? '高级版：' + formatTimeDate(new Date(currentMsg.expires)) + ' 到期' :
              currentMsg.planCode === PLAN_VERSIONS.ULTIMATE ? '旗舰版：' + formatTimeDate(new Date(currentMsg.expires)) + ' 到期' : currentMsg.planCode === PLAN_VERSIONS.ENTERPRISE ? '企业版：' + formatTimeDate(new Date(currentMsg.expires)) + ' 到期' : ''}
            </View>
            <View className='round'>{currentMsg.roomRound ===0 ? '' : '旗舰版单场： ' + currentMsg.roomRound + '场直播次数'}</View>
          </View> 
          <View className={tabCurrent === 0 ? 'edition' : 'nothing'}>
            <View><Text>{currentMsg.planCode === PLAN_VERSIONS.STANDARD ? '标准版 ' : currentMsg.planCode === PLAN_VERSIONS.ADVANCED ? '高级版' : currentMsg.planCode === PLAN_VERSIONS.ULTIMATE ? '旗舰版' : currentMsg.planCode === PLAN_VERSIONS.ENTERPRISE ? '企业版' : '免费版'}</Text></View>
          </View>
        </View>
      </View>
      {/* 套餐版本 */}
      <View className='main-model'>
        <AtTabs current={tabCurrent} tabList={tabList} onClick={handleClick.bind(this)}>
          {
            tabList.map((plans, index) => (
              <AtTabsPane current={index} index={index} key={index}>
                <View className='main-ability'>
                  {/* 套餐付费功能 */}
                  {
                    !!allPlans.priceMonth && plans.title != '免费版' && (
                      <View className='price-content'>
                        <ScrollView className='scroll-view' scrollX>
                          {
                            priceList.map((item, index1) => (
                              <View className={index1 === current ? "scroll-item current-item" : "scroll-item"} onClick={handleCheckPrice} data-index={index1} key={index1}>
                                <View className='item-style'>
                                  <View className='item-time'>{item.priceTime}</View>
                                  <View className='item-price'>￥<Text style='font-size:24px; font-weight: 500'>{item.total}</Text></View>
                                  {
                                    item.priceTime === '一年' && (
                                      <View>
                                        <View className='item-del'>￥{item.oldTotal}</View>
                                        <View className='item-discount'>立减{item.discount}元</View>
                                      </View>
                                    )
                                  }
                                </View>
                              </View>
                            ))
                          }
                        </ScrollView>
                        <View className='pay-price' onClick={goToPay}>
                          <Text>{currentMsg.planCode === allPlans.planCode ? '立刻以' + priceList[current].total + '元续费' : '立刻以' + priceList[current].total + '元升级'}</Text>
                        </View>
                      </View>
                    )
                  }
                  {
                    !!allPlans.priceRound && plans.title === '旗舰版单场' && (
                      <View className='price-content'>
                        <ScrollView className='scroll-view' scrollX>
                          {
                            roundsList.map((item, index1) => (
                              <View className={index1 === current ? "scroll-item1 current-item" : "scroll-item1"} onClick={handleCheckPrice} data-index={index1} key={index1}>
                                <View className='itemStyle'>
                                  <View className='item-num'>{item.rounds}
                                    {
                                      item.rounds !== '自定义' && (
                                        <Text className='site'>场</Text>
                                      )
                                    }
                                  </View>
                                  <View className='item-price'>￥{item.priceRound}/场</View>
                                </View>
                              </View>
                            ))
                          }
                        </ScrollView>
                        <View className='pay-price' onClick={goToPay}>
                          <Text> 立刻以{roundsList[current].total}元购买</Text>
                        </View>
                      </View>
                    )
                  }
                  <View className='main-title'> {plans.title === '高级版' ? '可用功能(包含标准版及以下功能)' : plans.title === '旗舰版' ? '可用功能(包含高级版及以下功能)' : plans.title === '企业版' ? '可用功能(包含旗舰版及以下功能)' : plans.title === '旗舰版单场' ? '可用功能(与旗舰版相同)' : '可用功能'} </View>
                  <ScrollView className='contentMsg' scrollY scrollWithAnimation >
                    <View className='ability'>
                      {options.map((item, index2) => (
                        <View className='ability-item' key={index2}>
                          <View className='item'>
                            <Image className='ability-item-img' src={item.logo}></Image>
                            <View className='ability-item-name' >{item.optionName}</View>
                          </View>
                          <View className='ability-item-desc'>{item.optionMemo}</View>
                        </View>
                      ))
                      }
                    </View>
                  </ScrollView>
                </View>
              </AtTabsPane>
            ))}
        </AtTabs>
        {/* 激活码 */}
        <View className='activation-code' onClick={goToActivation}>
          <Text>激活码激活</Text>
        </View>
      </View>
      {
        allPlans.planName === '旗舰版单场' && !!editRounds && (
          <AtModal isOpened={editRounds}>
            <AtModalHeader>自定义场次</AtModalHeader>
            <AtModalContent>
              <AtInput
                name='value'
                type='number'
                placeholder='请输入要购买的场次次数'
                value={inputVal}
                onChange={getInputTipsVal}
              />
            </AtModalContent>
            <AtModalAction> <Button onClick={setRoundsShow}>取消</Button> <Button onClick={setRounds} >确定</Button> </AtModalAction>
          </AtModal>
        )}
    </View >
  )
}
export default ServiceCenter